import postApis from '../../../apis/posts';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toastError } from '../../../components/toast-error';
import ErrorInfo from '../../../components/ui/ErrorInfo';
import List from '../../../components/ui/List';
import Card from '../../../components/ui/Card';
import Button from '../../../components/ui/Button';

const QUERY_KEY = 'my-post-collections';

type PostCollectionsProps = {
  onClick?: (collection: PostCollection) => void;
};

export default function PostCollections({ onClick }: PostCollectionsProps) {
  const quueryClient = useQueryClient();
  const { status, data, error } = useQuery({
    queryKey: [QUERY_KEY],
    queryFn: postApis.getPostCollections,
  });

  if (status === 'pending') {
    return <div>Loading...</div>;
  }

  if (status === 'error') {
    return <ErrorInfo error={error} />;
  }

  return (
    <Card noPadding className="w-60">
      <PostCollectionTitle onCreate={() => quueryClient.invalidateQueries({ queryKey: [QUERY_KEY] })} />
      <List items={data} toKey={(it) => it.id} onClick={onClick}>
        {(it) => <div>{it.title}</div>}
      </List>
    </Card>
  );
}

type PostCollectionTitleProps = {
  onCreate: (collection: PostCollection) => void;
};

function PostCollectionTitle({ onCreate }: PostCollectionTitleProps) {
  const [editing, setEditing] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('');

  const mutation = useMutation({
    mutationFn: postApis.createPostCollection,
    onSuccess: (collection) => {
      setTitle('');
      setEditing(false);
      onCreate(collection);
    },
    onError: toastError,
  });

  if (editing) {
    return (
      <div className="border-b px-4 py-2">
        {/* TODO: 数据校验 */}
        <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
        <button
          onClick={() => {
            setTitle('');
            setEditing(false);
          }}
        >
          取消
        </button>
        <button onClick={() => mutation.mutate({ title })}>确定</button>
      </div>
    );
  } else {
    return (
      <div className="flex justify-between border-b px-4 py-2 font-bold">
        分组 <Button size='sm' onClick={() => setEditing(true)}>添加</Button>
      </div>
    );
  }
}
